package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.imp;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.Alarm;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.AlarmService;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.FieldService;

public class AlarmServiceImp implements AlarmService {

	private Alarm alarm;
	private FieldService field;
	
	@Override
	public AlarmState getState() {
		if(field.getValue() == null)
			return AlarmState.OFF;
		switch(alarm.getOperator()){
			case EQUAL:
				if (field.getValue().intValue() == alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			case MAYOR:
				if (field.getValue().intValue() > alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			case MAYOR_EQUAL:
				if (field.getValue().intValue() >= alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			case MINOR:
				if (field.getValue().intValue() < alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			case MINOR_EQUAL:
				if (field.getValue().intValue() <= alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			case NOT_EQUAL:
				if (field.getValue().intValue() != alarm.getThreshold().intValue())
					return AlarmState.ON;
				else
					return AlarmState.OFF;
			default:
				break;
		
		}
		return AlarmState.OFF;
	}

	@Override
	public String getAlarmCriteria() {
		switch(alarm.getOperator()){
		case EQUAL:
			return " = " + alarm.getThreshold();
		case MAYOR:
			return " > " + alarm.getThreshold();
		case MAYOR_EQUAL:
			return " >= " + alarm.getThreshold();
		case MINOR:
			return " < " + alarm.getThreshold();
		case MINOR_EQUAL:
			return " <= " + alarm.getThreshold();
		case NOT_EQUAL:
			return " <> " + alarm.getThreshold();
		default:
			break;
		
		}
		return "";
	}

	@Override
	public String getFieldName() {
		
		return field.getName();
	}

	@Override
	public Integer getFieldValue() {
		return field.getValue();
	}

	@Override
	public String getAlarmName() {
		return alarm.getName();
	}

	@Override
	public String getDeviceAlarmName() {
		return field.getDeviceName();
	}

	@Override
	public boolean isActive() {
		return getState() == AlarmState.ON;
	}

	/**
	 * @return the alarm
	 */
	public Alarm getAlarm() {
		return alarm;
	}

	/**
	 * @param alarm the alarm to set
	 */
	public void setAlarm(Alarm alarm) {
		this.alarm = alarm;
	}

	/**
	 * @return the field
	 */
	public FieldService getField() {
		return field;
	}

	/**
	 * @param field the field to set
	 */
	public void setField(FieldService field) {
		this.field = field;
	}

}
